import { PureComponent } from 'react';
import './index.scss';
import NavBar from '../../components/NavBar';
import { http, baseURL } from '../../utils/http';
import { Toast } from 'antd-mobile';

class HouseList extends PureComponent {
  state = {
    houseList: [],
  };
  componentDidMount() {
    this.renderList();
  }
  render() {
    const { houseList } = this.state;
    const { hide } = this.props;
    return (
      <div className={'houseList' + (hide ? ' hide' : '')}>
        <div className='header'>
          <span className='title'>房屋列表</span>
          <span>更多房源</span>
        </div>
        <div className='item-list'>
          {houseList.map(item => (
            <div className='item' key={item.houseCode}>
              <div className='img-box'>
                <img src={`${baseURL}${item.houseImg}`} alt='img' />
              </div>
              <div className='info'>
                <div className='title'>{item.title}</div>
                <div className='desc'>{item.desc}</div>
                <div className='tags'>
                  {item.tags.map(item => (
                    <span key={item}>{item}</span>
                  ))}
                </div>
                <div className='price'>{item.price} 元/月</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  renderList() {
    // const {
    //   data: {
    //     body: { list },
    //   },
    // } = await http.get('/houses', { params: { cityId: this.props.id } });
    http.get('/houses', { params: { cityId: this.props.id } }).then(
      ({
        data: {
          body: { list },
        },
      }) => {
        this.setState({ houseList: list });
      }
    );
  }
}

export default class Map extends PureComponent {
  componentDidMount() {
    this.renderMap();
  }
  state = {
    title: '地图找房',
    houseList: [],
    curVilliageName: null,
    houseListHide: true,
  };
  render() {
    const { houseListHide, curVilliageName } = this.state;
    return (
      <div id='myMap'>
        <NavBar>{this.state.title}</NavBar>
        <div id='container'></div>
        <div className={'houseList' + (houseListHide ? ' hide' : '')}>
          <div className='header'>
            <span className='title'>房屋列表-{curVilliageName}</span>
            <span>更多房源</span>
          </div>
          <div className='item-list'>{this.renderVilliage()}</div>
        </div>
      </div>
    );
  }
  async renderMap() {
    const { BMap } = window;
    this.map = new BMap.Map('container');
    const myGeo = new BMap.Geocoder();
    const { label: cityName, value: areaId } = JSON.parse(window.localStorage.getItem('zf_city'));
    myGeo.getPoint(
      cityName,
      point => {
        this.map.addControl(new BMap.NavigationControl());
        this.map.addControl(new BMap.ScaleControl());
        // 渲染房屋数据
        this.renderLabels({ target: { id: areaId, point, name: cityName } }, 11);
      },
      cityName
    );
    this.map.addEventListener('movestart', () => {
      const { houseListHide } = this.state;
      !houseListHide && this.setState({ houseListHide: true });
    });
  }
  async renderLabels(e, scaleLevel, clear) {
    if (scaleLevel > 15) {
      this.renderViliage(e);
      return;
    }
    this.setState({ title: this.state.title + '-' + e.target.name });
    const { BMap } = window;
    Toast.loading('加载中...', 0, null, false);
    clear && clear();
    this.map.centerAndZoom(new BMap.Point(e.target.point.lng, e.target.point.lat), scaleLevel);
    const {
      data: { body: areaData },
    } = await http.get('/area/map', { params: { id: e.target.id } });
    areaData.map(({ coord: { longitude, latitude }, label, count, value }) =>
      this.renderContent({ longitude, latitude }, label, count, value)
    );
    Toast.hide();
  }
  renderContent({ longitude, latitude }, areaName, count, id) {
    const { BMap } = window;
    const label = new BMap.Label(null, {
      position: new BMap.Point(longitude, latitude),
      offset: new BMap.Size(-35, -35),
    });
    label.setContent(`
      <div class='label-wrapper'>
        <div class='area'>${areaName}</div>
        <div class='count'>${count}套</div>
      </div>
    `);
    label.setStyle({
      width: '70px',
      height: '70px',
      color: '#fff',
      'background-color': 'rgba(19,166,116,0.8)',
      border: 'solid 2px #fff',
      'border-radius': '50%',
      padding: '15px',
      'text-align': 'center',
      'line-height': '18px',
    });
    label.id = id;
    label.name = areaName;
    label.addEventListener('click', e => {
      this.renderLabels(e, this.getZoomLevel(), () => this.map.clearOverlays());
    });
    this.map.addOverlay(label);
  }
  // 获取小区租房信息
  async renderViliage(e) {
    const target = e.changedTouches[0];
    this.map.panBy(window.innerWidth / 2 - target.clientX, (window.innerHeight - 350) / 2 - target.clientY);
    const {
      data: {
        body: { list },
      },
    } = await http.get('/houses', { params: { cityId: e.target.id } });
    this.setState({ houseList: list, houseListHide: false, curVilliageName: e.target.name });
  }
  renderVilliage() {
    return this.state.houseList.map(item => (
      <div className='item' key={item.houseCode}>
        <div className='img-box'>
          <img src={`${baseURL}${item.houseImg}`} alt='img' />
        </div>
        <div className='info'>
          <div className='title'>{item.title}</div>
          <div className='desc'>{item.desc}</div>
          <div className='tags'>
            {item.tags.map(item => (
              <span key={item}>{item}</span>
            ))}
          </div>
          <div className='price'>{item.price} 元/月</div>
        </div>
      </div>
    ));
  }
  getZoomLevel() {
    const zoomLevel = this.map.getZoom();
    return zoomLevel + 2;
  }
}
